/*
 This file is part of BTStracker
		
    BTStracker is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    BTStracker is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Foobar.  If not, see <http://www.gnu.org/licenses/>.	
	author: azbest.pro (azbest.pro@gmail.com)
*/
package pl.vdl.azbest.mremote.cmd;

import java.util.Timer;
import java.util.TimerTask;
import java.util.logging.Logger;

import pl.vdl.azbest.log.LoggingTheGathering;
import pl.vdl.azbest.mremote.CommComunicator;
import pl.vdl.azbest.mremote.com.CConnect;
import pl.vdl.azbest.mremote.com.CSConnected;

public class Cmd_sendCommCommand implements Command, Runnable {

	private String cmd;

	public Cmd_sendCommCommand(String cmd) {
		this.cmd = cmd;
	}

	public void execute() {
		/*
		 * // try send command right away //System.out.println("Executing
		 * Cmd_sendCommCommand first time"); if (trySendCommand()) return; // if
		 * failure wiat a while and send again ... // logger.info("Sending
		 * command to comm port: " + cmd);
		 * 
		 * //System.out.println("Turn on timer and wait 1 s"); final Timer timer =
		 * new Timer(); class MyTimerTask extends TimerTask { public void run() {
		 * if (trySendCommand()) { return; } else { // if failure - again ...
		 * //System.out.println("wait again 1s..."); timer.schedule(this, 1000); } } }
		 * 
		 * class CommandExecutor implements Runnable { public void run() {
		 * timer.schedule(new MyTimerTask(), 1000);
		 * //System.out.println("Command Executor ends."); } } class NextLoader
		 * implements Runnable {
		 * 
		 * public void run() { CommandExecutor cxe = new CommandExecutor();
		 * Thread t = new Thread(cxe); t.start(); synchronized (t) { try {
		 * t.wait(); // after command is execuuted - start another command }
		 * catch (InterruptedException e) { e.printStackTrace(); } } } }
		 */

	}

	private boolean trySendCommand() {
		if (cmd != null
				&& CConnect.getInstance().getState() instanceof CSConnected) {
			CConnect.getInstance().write(cmd);
			logger.info("OK - Command has successfuly executed its code ");

			return true;
		}
		// System.out.println(" - Cannot invoke !");

		logger
				.info("NO - Command have to wait for a while for comm to stop sending data and for Comm reeader to turn tu Connected state.");
		return false;

	}

	private Logger logger = Logger.getLogger(getClass().getName());

	private CConnect conn;
	{
		LoggingTheGathering.addPath(getClass().getName());
	}

	public void run() {
		Thread.currentThread().setName("Cmd_sendCommCommand: " + cmd);
		synchronized (this) {

			// try send command right away
			// System.out.println("Executing Cmd_sendCommCommand first time");
			if (trySendCommand())
				return;
			// if failure wiat a while and send again ...
			// logger.info("Sending command to comm port: " + cmd);

			// System.out.println("Turn on timer and wait 1 s");
			final Timer timer = new Timer();
			class MyTimerTask extends TimerTask {
				public void run() {
					synchronized (timer) {

						Thread.currentThread().setName(
								"CMD timer for CONNECTED state check");
						if (trySendCommand()) {
							// call MRTomato tah he can load new one
							timer.notify();

							return;
						} else {
							// if failure - again ...
							// System.out.println("wait again 1s...");
							timer.schedule(new MyTimerTask(), 1000);
						}
					}
				}
			}
			timer.schedule(new MyTimerTask(), 1000);
			synchronized (timer) {
				// waiting for timer to end...
				try {
					timer.wait();
					logger
							.info("_____________DONE with waiting for my timer !!!!");
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				// when timer notifies us about his end we can notify MrTomato
				// about our end :)
				notify();
			}// synchro - timer2Cmd
		}// sychro Cmd2MrTomato
	}// run

}
